package com.realgodo.site.service.space;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.space.Space;
import com.realgodo.site.entity.space.SpacePoint;

@Service("spacePointManager")
@Transactional
public class SpacePointManager extends DefaultEntityManager<SpacePoint, Long> {
	@Autowired
	protected SessionFactory sessionFactory;

	@Autowired
	private SpaceManager spaceManager;

	public boolean increasePoint(Long spaceId) {
		boolean flag = false;
		SpacePoint point = this.getSpacePointBySpace(spaceId);

		Date current = new Date();
		if ((current.getTime() - point.getLastLogin().getTime()) > 86400000L) {
			point.setPoint(point.getPoint() + 1L);
			point.setLastLogin(current);
			this.save(point);
			flag = true;
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public SpacePoint getSpacePointBySpace(Long spaceId) {

		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o from SpacePoint o where o.space.id = " + spaceId;
		Query q = session.createQuery(hql);
		List list = q.list();
		SpacePoint point = null;
		if (list != null && !list.isEmpty()) {
			point = (SpacePoint) list.get(0);
		} else {// 无积分记录就创建一个
			point = new SpacePoint();
			Space space = spaceManager.get(spaceId);
			point.setSpace(space);
			point = (SpacePoint) this.saveMerge(point);
		}
		return point;
	}

}
